import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: 祺诺
 * @Name; xqf
 * @Date: 2020/12/24 19:41
 */
@WebServlet("/text1")
public class text1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        Cookie cookie = CookieUtils.findCookie(req, "time");
        if(cookie==null){
            //首次访问
            resp.getWriter().write("欢迎访问");
        }else{
            //如果不是首次访问 取出这个cookie键值对保存的值
            //利用时间格式 和 时间 类进行将存入的毫秒值转换为正常的时间参数 并且展示出来
            String value = cookie.getValue();
            SimpleDateFormat spf = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
            Date date = new Date(Long.parseLong(value));
            resp.getWriter().write("您上次的访问时间为"+ spf.format(date));
        }
        //不论前面有木有访问过  都需要重新将这次的访问时间计入 打包到cookie对象中 通过响应体写出
        Cookie t = new Cookie("time", System.currentTimeMillis() + "");
        //设置存活时间
        t.setMaxAge(60);
        //写入cookie
        resp.addCookie(t);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
